<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/9/29
 * Time: 15:37
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Ordertui extends Base
{
    /**
     * 售后订单数据
     */
    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            $map['o.is_delete'] = 0;
            $map['o.tui_type'] = ['in','1,2'];
            if(isset($n_title)&&$n_title!="")
            {
                $map['o.order_erp_wl_no|o.express_no|user_username|user_phone'] = ['like',"%" . $n_title . "%"];
            }
            if(isset($contract)&&$contract!="")
            {
                if($contract == 1){
                    $map['tui_user_son_id'] = ' ';
                }else{
                    $map['tui_user_son_id'] = ['>',0];
                }

            }
            if(isset($type) && $type){
                if($type == 1){
                    $map['o.status'] = 1;
                }
                if($type == 2){
                    $map['o.status'] = 2;
                    $map['o.is_send'] = 0;
                }
                if($type == 3){
                    $map['o.status'] = 2;
                    $map['o.is_send'] = 1;
                }
                if($type == 4){
                    $map['o.status'] = 3;
                }
            }
            if(isset($tuitype) && $tuitype){
                $map['o.type'] = $tuitype;
            }
            if(isset($orderid) && $orderid){
                $map['o.order_id'] = $orderid;
            }

            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'o.*,user_username,user_phone,d.goods_id';
            $count = Db::table('up_self_order_tui')->alias('o')
                ->join('up_self_order_detail d','o.order_detail_id=d.detail_id','LEFT')
//                ->join('up_self_goods g','d.goods_id=g.good_id','LEFT')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->group('order_erp_wl_no')
                ->count();// 获取总条数
            $lists = Db::table('up_self_order_tui')->alias('o')
                ->join('up_self_order_detail d','o.order_detail_id=d.detail_id','LEFT')
//                ->join('up_self_goods g','d.goods_id=g.good_id','LEFT')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->group('order_erp_wl_no')
                ->order('status ASC,created_at DESC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            if($lists){
                foreach ($lists as $k=>$v){
                    $contract = Db::table('up_self_order')->where('order_id', $v['order_id'])->value('order_contract');
                    $lists[$k]['order_contract'] = $contract;
                    if($contract == 1){
                        $lists[$k]['good_name'] = Db::table('up_self_goods')
                            ->where('good_id',$v['goods_id'])->value('good_name');
                    }else{
                        $lists[$k]['good_name'] = Db::table('up_goods')
                            ->where('good_id',$v['goods_id'])->value('good_name');
                    }
                    //总金额，总数量
                    $lists[$k]['all_money'] = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$v['order_erp_wl_no'])->sum('should_money');
                    $lists[$k]['all_num'] = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$v['order_erp_wl_no'])->sum('refund_num');
                    $tui = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$v['order_erp_wl_no'])
                        ->where('status',2)
                        ->where('is_send',0)
//                        ->where('tui_type',2)
                        ->where('type',2)
                        ->field('tui_id')
                        ->find();
                    $lists[$k]['tuikuan'] = 1;
                    if($tui){
                        $lists[$k]['tuikuan'] = 2;
                    }
                    $huan = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$v['order_erp_wl_no'])
                        ->where('status',2)
                        ->where('is_send',0)
                        ->where('tui_type',1) //只有自营的才可以有发货的资格
                        ->where('type',1)
                        ->field('tui_id')
                        ->find();
                    $lists[$k]['fahuo'] = 1;
                    if($huan){
                        $lists[$k]['fahuo'] = 2;
                    }
                    $gai = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$v['order_erp_wl_no'])
                        ->where('status',2)
                        ->where('is_send',1)
//                        ->where('tui_type',1)
                        ->where('type',1)
                        ->field('tui_id')
                        ->find();
                    $lists[$k]['gai'] = 1;
                    if($gai){
                        $lists[$k]['gai'] = 2;
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch('ordertui/index');
    }

    /**
     * 同意
     */
    public function orderYesSend(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $tui = Db::table('up_self_order_tui')
                ->where('tui_id',$tui_id)
                ->field('status,order_id,order_detail_id,user_id,tui_type,order_erp_wl_no')
                ->find();
            if($tui['status'] != 1){
                return json(['code'=>100,'msg'=>'只有待处理的售后订单才可以操作']);
            }
            if(empty($fahuo)){
                //拒绝deids
                $jj_deids = Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                    ->column('order_detail_id');
                $param  = [
                    'status'=>3,
                    'status_time'=>$today,
                    'merchant_remark'=>$merchant_remark,
                    'updated_at'=>$today,
                ];
                Db::startTrans();
                try{
                    Db::table('up_self_order_detail')
                        ->where('detail_id', 'in',$jj_deids)
                        ->setField('refund_status',2);
                    Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                        ->update($param);
                    //---------------------------------------
                    $this->changeOrder($tui['order_id']);
                    //---------------------------------------
                    Db::commit();
                    return json(['code'=>200,'msg'=>'成功']);
                }catch (\Exception $e) {
                    Db::rollback();
                    return json(['code'=>100,'msg'=>'失败']);
                }
            }else{
                $param  = [
                    'status'=>2,
                    'status_time'=>$today,
                    'merchant_remark'=>$merchant_remark,
                    'updated_at'=>$today,
                ];
                $tuids = implode($fahuo,',');
                try{
                    Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                        ->where('tui_id','in',$tuids)
                        ->update($param);
                    $now_count = count($fahuo);
                    $all_count = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                        ->count();
                    //start如果不是全选，拒绝的来一下
                    if($now_count != $all_count){
                        $param  = [
                            'status'=>3,
                            'status_time'=>$today,
                            'merchant_remark'=>$merchant_remark,
                            'updated_at'=>$today,
                        ];
                        $jj_deids = Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                            ->where('tui_id','not in',$tuids)
                            ->column('order_detail_id');
                        Db::table('up_self_order_detail')
                            ->where('detail_id', 'in',$jj_deids)
                            ->setField('refund_status',2);
                        Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no',$tui['order_erp_wl_no'])
                            ->where('tui_id','not in',$tuids)
                            ->update($param);
                    }
                    //endt如果不是全选，拒绝的来一下
                    Db::commit();
                    $title = '退换货成功通知';
                    $content = '由客服检验退换货没有问题，在后台点击确认退货以后友情提醒：货物已收，经检验符合退换货要求。如需换货，系统会根据您的提交换货信息进行重新发货，请耐心等待；如需退货，款项将在7个工作日内原路退回您的付款账户。';
                    allInNotice($title,$content,4,$tui['user_id'],$tui['order_id'],$tui['tui_type']);
                    //TODO：增补的发送给erp
                    try{
                        $this->Jpush(1, $tui['user_id'], '售后成功通知', ['n_id' => $tui['order_id'],'type' => $tui['tui_type'],'n_type' => 4]);
                    }catch(\Exception $e){

                    }
                    return json(['code'=>200,'msg'=>'成功']);
                }catch (\Exception $e) {
                    Db::rollback();
                    return json(['code'=>100,'msg'=>'失败']);
                }
            }
        }
        $data = Db::table('up_self_order_tui')
            ->where('tui_id',$tui_id)
            ->field('status,order_id,tui_user_son_id,order_erp_wl_no')
            ->find();
        if($data['status'] != 1){
            return '只有待处理的售后订单才可以同意！';
            exit();
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$data['order_id'])
            ->find();
        //----------------------------------------------
        $good_tabld = 'up_self_goods';
        if($data['tui_user_son_id'] != 0){
            $good_tabld = 'up_goods';
        }
        $field = 'tui_id,num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,type,status,is_send';
        $details = Db::table('up_self_order_tui')->alias('o')
            ->join('up_self_order_detail od','o.order_detail_id=od.detail_id','LEFT')
            ->join("$good_tabld g",'od.goods_id=g.good_id','LEFT')
            ->where('order_erp_wl_no',$data['order_erp_wl_no'])
            ->field($field)
            ->select();
        return $this->fetch('ordertui/orderyessend',['data'=>$order,'type'=>$type,'details'=>$details,'tui_id'=>$tui_id]);
    }

    /**
     * 发货:发货和修改都走这了
     *
     */
    public function orderSend(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $order_id = Db::table('up_self_order_tui')
                ->where('order_erp_wl_no',$order_erp_wl_no)
                ->where('status',2)
                ->column('order_id');
            $tui = Db::table('up_self_order_tui')
                ->where('order_erp_wl_no',$order_erp_wl_no)
                ->where('status',2)
                ->column('order_detail_id');
            $param  = [
                'is_send'=>1,
                'send_time'=>$today,
                'updated_at'=>$today,
                'merchant_express'=>trim($merchant_express,' '),
                'merchant_express_no'=>trim($merchant_express_no,' '),
            ];
            Db::startTrans();
            try{
                //---------------------------------------
                $this->changeOrder($order_id);
                //---------------------------------------
                Db::table('up_self_order_detail')
                    ->where('detail_id', 'in',$tui)
                    ->setField('refund_status',2);
                Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$order_erp_wl_no)
                    ->where('status',2)
                    ->update($param);
                Db::commit();
                return json(['code'=>200,'msg'=>'成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code'=>100,'msg'=>'失败']);
            }
        }
//        return '暂未开放！';
//        exit();
        $tui = Db::table('up_self_order_tui')
            ->where('order_erp_wl_no',$order_erp_wl_no)
            ->where('status',2)
            ->field('tui_id,merchant_express,merchant_express_no,order_id')
            ->find();
        $order = Db::table('up_self_order')
            ->where('order_id',$tui['order_id'])
            ->field('name,mobile,address')
            ->find();
        return $this->fetch('ordertui/ordersend',['data'=>$order,'tui'=>$tui]);
    }

    /**
     * 退款：TODO：不区分是自营还是增补，如果要把自营拿出去的话，就得做区分了->where('tui_type',2)
     * @return \think\response\Json
     */
    public function orderTuiMoney(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            $tui = Db::table('up_self_order_tui')
                ->where('order_erp_wl_no',$order_erp_wl_no)
                ->where('status',2)
                ->where('is_send',0)
//                ->where('tui_type',2)
                ->where('type',2)
                ->field('status,is_send,order_detail_id,order_id,order_no,order_erp_wl_no')
                ->find();
            if(!$tui){
                return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
            }
            $order = Db::table('up_self_order')
                ->where('order_id',$tui['order_id'])
                ->field('total_price,pay_type,order_no,user_id,order_contract,order_query_id')
                ->find();
            $refund_price = round($refund_price,2);
            if($refund_price <= 0 || $refund_price > $order['total_price']){
                return json(['code'=>100,'msg'=>'退款金额不能低于0且不能大于订单金额！']);
            }
            $param  = [
                'is_send' => 1,
                'send_time' => $today,
                'refund_price'=>$refund_price,
                'merchant_remark'=>$merchant_remark,
                'updated_at' => $today,
            ];
            $payInfo = [
                'money' => $refund_price,
                'number' => $order['order_no']
            ];
            $refundNo = $tui['order_erp_wl_no'];
            if($order['pay_type'] == 1){ //微信
                $tuiwx = new \app\admin\controller\Tuiwx();
                $res = $tuiwx->refundWx($payInfo,$refundNo);
            }elseif ($order['pay_type'] == 2){ //支付宝
                $tuiali = new \app\admin\controller\Tuiali();
                $res = $tuiali->refund($payInfo,$refundNo);
            }else{
                $tuiali = new \app\admin\controller\Tuiupacp();
                $res = $tuiali->UpacpTuiKuan($refundNo,$refund_price,$order['order_query_id']);
            }
            if($res['status'] == 200){
                Db::startTrans();
                try{
                    $jj_deids = Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$order_erp_wl_no)
                        ->where('status',2)
                        ->where('is_send',0)
                        ->column('order_detail_id');
                    Db::table('up_self_order_detail')
                        ->where('detail_id', 'in',$jj_deids)
                        ->setField('refund_status',2);
                    Db::table('up_self_order_tui')
                        ->where('order_erp_wl_no',$order_erp_wl_no)
                        ->where('status',2)
                        ->where('is_send',0)
                        ->update($param);
                    //---------------------------------------
                    $this->changeOrder($tui['order_id']);
                    //---------------------------------------
                    Db::commit();
                    //平台退款
                    allInRevenue(2,$refund_price,$order['user_id'],$order['order_contract'],$tui['order_id'],session('username'),$tui_id);
                    return json(['code'=>200,'msg'=>'成功']);
                }catch (\Exception $e) {
                    Db::rollback();
                    return json(['code'=>100,'msg'=>'订单状态修改失败，请联系管理员！']);
                }
            }else{
                return json(['code'=>100,'msg'=>$res['msg']]);
            }
        }
        $tui = Db::table('up_self_order_tui')
            ->where('order_erp_wl_no',$order_erp_wl_no)
            ->where('status',2)
            ->where('is_send',0)
//            ->where('tui_type',2)
            ->where('type',2)
            ->field('status,is_send,order_detail_id,order_id,order_no,order_erp_wl_no')
            ->find();
        if(!$tui){
            return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
        }
        return $this->fetch('ordertui/ordertuimoney',['tui_id'=>$order_erp_wl_no]);
    }




    /**
     * 订单详情
     */
    public function orderInfo(){
        $tui_id = input('tui_id');
        $good_tabld = 'up_self_goods';
        $field = 'o.*,user_username,user_phone';
        $data = Db::table('up_self_order_tui')->alias('o')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->where('tui_id',$tui_id)
            ->field($field)
            ->find();
        if($data['tui_user_son_id'] != 0){
            $good_tabld = 'up_goods';
        }
        //总金额，总数量
        $data['all_money'] = Db::table('up_self_order_tui')
            ->where('order_erp_wl_no',$data['order_erp_wl_no'])->sum('should_money');
        $data['all_num'] = Db::table('up_self_order_tui')
            ->where('order_erp_wl_no',$data['order_erp_wl_no'])->sum('refund_num');

        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,type,status,is_send';
        $details = Db::table('up_self_order_tui')->alias('o')
            ->join('up_self_order_detail od','o.order_detail_id=od.detail_id','LEFT')
            ->join("$good_tabld g",'od.goods_id=g.good_id','LEFT')
            ->where('order_erp_wl_no',$data['order_erp_wl_no'])
            ->field($field)
            ->select();
        return $this->fetch('ordertui/orderinfo',['data'=>$data,'goods'=>$details]);
    }

    //导出
    public function excelOutOrder()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['o.tui_type'] = ['in','1,2'];
        if(isset($n_title)&&$n_title!="")
        {
            $map['o.order_erp_wl_no|o.express_no|user_username|user_phone'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($contract)&&$contract!="")
        {
            if($contract == 1){
                $map['tui_user_son_id'] = ' ';
            }else{
                $map['tui_user_son_id'] = ['>',0];
            }

        }
        if(isset($type) && $type){
            if($type == 1){
                $map['o.status'] = 1;
            }
            if($type == 2){
                $map['o.status'] = 2;
                $map['o.is_send'] = 0;
            }
            if($type == 3){
                $map['o.status'] = 2;
                $map['o.is_send'] = 1;
            }
            if($type == 4){
                $map['o.status'] = 3;
            }
        }
        if(isset($tuitype) && $tuitype){
            $map['o.type'] = $tuitype;
        }
        if(isset($orderid) && $orderid){
            $map['o.order_id'] = $orderid;
        }
        $field = [
            'order_erp_wl_no','order_id','express','express_no','user_username',
            'user_phone','o.created_at','o.type','tui_type','o.remark',
            'status','is_send'
        ];
        $data = Db::table('up_self_order_tui')->alias('o')
            ->join('up_self_order_detail d','o.order_detail_id=d.detail_id','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->where($map)
            ->group('order_erp_wl_no')
            ->field($field)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                $lists[$k]['all_money'] = Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$v['order_erp_wl_no'])->sum('should_money');
                $lists[$k]['all_num'] = Db::table('up_self_order_tui')
                    ->where('order_erp_wl_no',$v['order_erp_wl_no'])->sum('refund_num');
            }
            $cellname = [
                '退货单号', '原订单id', '退货物流', '退货单号', '用户昵称',
                '用户电话', '创建时间', '售后类型', '订单类型', '备注',
                '售后状态', '售后进度', '退款金额（退货类型时）', '校服数量'
            ];
            $status = ['type','tui_type','status','is_send'];
            $values = [
                'type' => [1 => '换货',2 => '退货']
                ,'tui_type' => [1 => '自营',2 => '增补',3 => '统购']
                ,'status' => [1 => '待处理',2 => '已同意',3 => '已拒绝']
                ,'is_send' => [0 => '进行中',1 => '已结束']
            ];
            $res = exportExcel('afterSales',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    //导出
    public function excelOutDetail()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['o.tui_type'] = ['in','1,2'];
        if(isset($n_title)&&$n_title!="")
        {
            $map['o.order_erp_wl_no|o.express_no|user_username|user_phone'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($contract)&&$contract!="")
        {
            if($contract == 1){
                $map['tui_user_son_id'] = ' ';
            }else{
                $map['tui_user_son_id'] = ['>',0];
            }

        }
        if(isset($type) && $type){
            if($type == 1){
                $map['o.status'] = 1;
            }
            if($type == 2){
                $map['o.status'] = 2;
                $map['o.is_send'] = 0;
            }
            if($type == 3){
                $map['o.status'] = 2;
                $map['o.is_send'] = 1;
            }
            if($type == 4){
                $map['o.status'] = 3;
            }
        }
        if(isset($tuitype) && $tuitype){
            $map['o.type'] = $tuitype;
        }
        if(isset($orderid) && $orderid){
            $map['o.order_id'] = $orderid;
        }
        $field = [
            'order_erp_wl_no','unit_price','num','attr_id','goods_info',
            'goods_coding_unique','user_username','user_phone','o.created_at','o.remark',
            'o.express','express_no','o.type','tui_type','status',
            'is_send'
        ];
        $data = Db::table('up_self_order_tui')->alias('o')
            ->join('up_self_order_detail d','o.order_detail_id=d.detail_id','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->where($map)
            ->field($field)
            ->select();
        if($data){
            //总金额，总数量
            $cellname = [
                '退货单号', '单价', '数量', '尺码', '产品信息',
                '唯一条码', '用户昵称', '用户电话', '创建时间', '备注',
                '退货物流', '退货单号', '售后类型', '订单类型', '售后状态',
                '售后进度'
            ];
            $status = ['type','tui_type','status','is_send'];
            $values = [
                'type' => [1 => '换货',2 => '退货']
                ,'tui_type' => [1 => '自营',2 => '增补',3 => '统购']
                ,'status' => [1 => '待处理',2 => '已同意',3 => '已拒绝']
                ,'is_send' => [0 => '进行中',1 => '已结束']
            ];
            $res = exportExcel('afterSales',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}